const map = new Map<string, number>([
  ["apple", 20],
  ["orange", 10],
]);

console.log(map);
console.log(map.get("apple"));
map.set("banna", 2.99);

console.log(map);

// map实现
class MyMap<K, V> {
  constructor(private map: Array<[K, V]> = []) {}

  has(k: K): boolean {
    return this.map.some(([key]) => key === k);
  }

  get(key: K): V | undefined {
    return this.map.find(([k]) => k === key)?.[1]; // 返回V或者undefined，这里?.[1] 返回的就是undefined
  }

  set(key: K, value: V): void {
    // 先判断是否有，如果就做替换，没有就添加
    if (this.has(key)) {
      this.map = this.map.map(([k, v]) => (k === key ? [k, value] : [k, v]));
    } else {
      this.map.push([key, value]);
    }
  }

  delete(key: K): void {
    this.map = this.map.filter(([k]) => k !== key);
  }

  get size(): number {
    return this.map.length;
  }

  clear(): void {
    this.map = [];
  }
}

const map1 = new MyMap([["hello", 5]]);
console.log(map1);
console.log(map1.get("hello"));
console.log(map1.has("hello1"));
console.log(map1.delete("hello")); // 返回undefined
console.log(map1); // 删除之后就为空数组
map1.set("app", 20);
map1.set("app", 3); // key相同，覆盖
map1.set("Aphone", 90);
console.log(map1.size);
console.log(map1);

map1.clear(); // 清空数组
console.log(map1);
